<template>
  <a-modal
    v-model:open="visible"
    title="修改密码"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    :width="500"
    okText="确认修改"
    cancelText="取消"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      layout="vertical"
      name="changePasswordForm"
    >
      <a-form-item label="账号" name="account">
        <a-input
          v-model:value="formState.account"
          placeholder="请输入您的账号"
          :disabled="confirmLoading"
        />
      </a-form-item>

      <a-form-item label="邮箱" name="phoneNum">
        <a-input
          v-model:value="formState.phoneNum"
          placeholder="请输入绑定的邮箱"
          :disabled="confirmLoading"
        />
      </a-form-item>

      <a-form-item label="验证码" name="verifyCode" required>
        <a-input-group>
          <a-row :gutter="8" style="width: 100%">
            <a-col :span="14">
              <a-input
                v-model:value="formState.verifyCode"
                placeholder="请输入收到的验证码"
                :disabled="confirmLoading"
              />
            </a-col>
            <a-col :span="6">
              <a-button
                type="primary"
                block
                @click="sendSmsCode"
                :disabled="smsButtonEnabled === false || confirmLoading"
              >
                {{ smsButtonText }}
              </a-button>
            </a-col>
          </a-row>
        </a-input-group>
      </a-form-item>

      <a-form-item label="新密码" name="password" required>
        <a-input-password
          v-model:value="formState.password"
          placeholder="请输入新密码"
          :disabled="confirmLoading"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import Http from '@/api/http'
import { Form, message } from 'ant-design-vue'
import { computed, reactive, ref } from 'vue'

const { useForm } = Form

// Props 用于控制模态框显示/隐藏
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})

// Emit 用于更新父组件的 v-model
const emit = defineEmits(['update:modelValue', 'submit'])
// 模态框显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  }
})

// 表单数据
const formState = reactive({
  account: '',
  phoneNum: '',
  verifyCode: '',
  password: ''
})

// 表单引用
const formRef = ref()

// 表单验证规则
const rules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  phoneNum: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  verifyCode: [
    { required: true, message: '请输入短信验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', pattern: /^\d{6}$/, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少6位', trigger: 'blur' }
  ]
}

// 使用 useForm 进行表单验证
const { resetFields, validate, validateFields } = useForm(formState, rules)

// 确认按钮加载状态
const confirmLoading = ref(false)
const countdown = ref(0)
// 发送验证码按钮状态
const smsButtonEnabled = ref(true)
const smsButtonText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}秒后重发` : '发送验证码'
})

// 发送验证码
const sendSmsCode = () => {
  const pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!pattern.test(formState.phoneNum)) {
    message.error('邮箱格式不正确')
    return
  }
  formState.verifyCode = ''
  smsButtonEnabled.value = false
  Http.post('/auth/sendVerifyCode', formState).then((res) => {
    if (res.data === true) {
      message.success('验证码已发送')
      startCountdown()
    } else {
      message.error('发送失败，请稍后重试')
    }
  })
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      countdown.value = 0
    }
  }, 1000)
}

// 确认修改 (提交表单)
const handleOk = async () => {
  formRef.value.validateFields().then(() => {
    confirmLoading.value = true
    Http.post('/auth/modifyPwd', formState)
      .then((res) => {
        if (res.code === 200) {
          message.success('密码修改成功！')
          // 通知父组件提交成功并关闭模态框
          emit('submit', { ...formState })
          visible.value = false // 关闭模态框
          resetFields() // 重置表单
        }
      })
      .finally(() => {
        confirmLoading.value = false
      })
  })
}

// 取消/关闭模态框
const handleCancel = () => {
  // 重置表单和状态
  resetFields()
  smsButtonEnabled.value = true
  countdown.value = 0
  // confirmLoading 已在 handleOk 中处理
}
</script>

<style scoped>
/* 可以根据需要添加自定义样式 */
</style>
